﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace TempHumidityMonitor {
    public class ExportHelper {
        public static void ExportToExcel(DataTable dt, IWin32Window owner) {
            SaveFileDialog sfd = new SaveFileDialog {
                Filter = "Excel文件|*.xlsx",
                Title = "导出数据"
            };

            if (sfd.ShowDialog(owner) != DialogResult.OK)
                return;

            try {
                using (var workbook = new XSSFWorkbook())
                using (var fs = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write)) {
                    ISheet sheet = workbook.CreateSheet("历史数据");
                    IRow headerRow = sheet.CreateRow(0);

                    for (int i = 0; i < dt.Columns.Count; i++)
                        headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);

                    for (int i = 0; i < dt.Rows.Count; i++) {
                        IRow row = sheet.CreateRow(i + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                            row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
                    }

                    workbook.Write(fs);
                }

                MessageBox.Show(owner, "导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex) {
                MessageBox.Show(owner, "导出失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}